

#include "ohos_init.h"          // 用于初始化服务(services)和功能(features)
#include "cmsis_os2.h"          // CMSIS-RTOS API V2

#include "drv_sensor.h"   // 环境监测板AHT20数字温湿度传感器接口
#include "wifi_connecter.h"     // easy wifi (station模式)
#include "mqtt_task.h"          // MQTT接口
#include "common.h"
#include "oled_ssd1306.h"
#include "drv_pwmRGBLight.h"
#include "cJSON.h"
#include "drv_adcMQ2.h"

/**************************************************************************
 * 
 * 
 * 
 * 
 * 
 ***************************************************************************/



/**
 * @brief 
 * 
 * @param arg 
 */
static void mainTask_threadHandle(void *arg)
{
    (void)arg;
    static uint32_t cnt_stat_timer = 0;
    
    osal_printk("\r---------------------- main thread ------------------------\n");

    initOled();

    AdcMQ2Entry();

    init_BmsInfoDefault();

    updateBmsInfo_TaskEntry();

    connectWifi();
    
    waitIpaddrStatus();

    // 等待1s，否则会出现TCP连接失败
    osDelay(100);

    mqttClientCreate_TaskEntry();

    // 工作循环
    while (1)
    {
        if (cnt_stat_timer % 5 == 0) // 500mS
        {
            readAht20TempHumiValue();
        }

        if (cnt_stat_timer % 10 == 0) // 1S
        {
            // osal_printk("\r[long] Info temp: %.2f; humi: %.2f\n", temperature, humidity);
            // osal_printk("\r[long] Info %s; %s\n", templine, humiline);
            SystemCntTickHandler();
        }

        if (cnt_stat_timer % 2 == 0) // 
        {
            // pwmRGBLightBlink();
        }

        // osal_printk("\r[long] cnt timer = %d \n", cnt_stat_timer);
        cnt_stat_timer ++;
        cnt_stat_timer = cnt_stat_timer%1000;
        osDelay(10);  // delay time 单位100ms                                 

    }
}


// 入口函数
static void mainFuncTask_Create(void)
{
    // 初始化AHT20数字温湿度传感器
    InitTempHumiSensor();

    initDIDO();
    
    // initPwmRGBLight();

    // 定义线程属性
    osThreadAttr_t attr;
    attr.name = "mqtt Task thread";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = (1024 * 10);
    attr.priority = osPriorityNormal;

    // 创建线程
    if (osThreadNew(mainTask_threadHandle, NULL, &attr) == NULL)
    {
        osal_printk("[Error] fail to create mqtt Task ... \n");
    }
}

// 运行入口函数
APP_FEATURE_INIT(mainFuncTask_Create);

